package org.xg.study.servlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName LoginTimeSessionServlet
 * @date 2021/9/24 14:42
 **/
@WebServlet("/loginTimeSession")
public class LoginTimeSessionServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter printWriter = resp.getWriter();
        printWriter.write("<h1>编程帮 www.biancheng.net</h1>" + "<h3>编程帮，程序猿的好帮手，欢迎您的到来！</h3>");
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date createTime = new Date(req.getSession().getCreationTime());
        Date lastAccessTime = new Date(req.getSession().getLastAccessedTime());
        String sDate = sdf.format(date);
        req.getSession().setAttribute("lastTime", sDate);
        req.getSession().setMaxInactiveInterval(100);
        printWriter.write("<h3>当前时间：" + sDate + "</h3>"
                + "当前会话的SessionID：" + req.getSession().getId() + "<br/>"
                + "创建此会话的时间为：" + sdf.format(createTime) + "<br/>"
                + "Session上次关联的时间为：" + sdf.format(lastAccessTime) + "<br/>"
                + "会话保持打开状态的最大时间间隔：" + req.getSession().getMaxInactiveInterval() + "<br/>");
        String url = resp.encodeURL("/ServletSession/second");
        printWriter.write("<a href=" + url + ">再次访问</a>");
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
